package com.ruoyi.dynamic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.CollectionUtils;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.dynamic.mapper.RoomWishMapper;
import com.ruoyi.dynamic.model.constant.DynamicConstant;
import com.ruoyi.dynamic.model.constant.RoomChatRoomKvConstant;
import com.ruoyi.dynamic.model.pojo.entity.Gift;
import com.ruoyi.dynamic.model.pojo.entity.Room;
import com.ruoyi.dynamic.model.pojo.entity.RoomGiftRecord;
import com.ruoyi.dynamic.model.pojo.entity.RoomWish;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomSetUpdateRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomUserSearchRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomWishAddOrEditRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomWishCloseRequest;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomSetResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomWishGiveInfoResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomWishInfoResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomWishResult;
import com.ruoyi.dynamic.service.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 房间心愿单 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-12-13
 */
@Service
public class RoomWishServiceImpl extends ServiceImpl<RoomWishMapper, RoomWish> implements IRoomWishService {

    @Autowired
    private IRoomService iRoomService;
    @Autowired
    private IRoomGiftRecordService iRoomGiftRecordService;
    @Autowired
    private IGiftService iGiftService;
    @Autowired
    private IRoomSetService iRoomSetService;
    @Autowired
    private IMessageService iMessageService;

    @Override
    public List<AppRoomWishResult> listPage(Long userId, AppRoomUserSearchRequest request) {
        Room verify = iRoomService.verify(request.getRoomId());
        return lambdaQuery()
                .eq(RoomWish::getUserId, verify.getUserId())
                .eq(RoomWish::getStatus, DynamicConstant.CheckStatus.YES)
                .orderByAsc(RoomWish::getSort)
                .list()
                .stream()
                .map(res -> {
                    return AppRoomWishResult.builder()
                            .giftId(res.getGiftId())
                            .giftName(res.getGiftName())
                            .giveNumber(iRoomGiftRecordService.getGiftGiveNumberByRoomId(verify.getId(), res.getGiftId(), res.getOpenTime()))
                            .number(res.getNumber())
                            .id(res.getId())
                            .price(res.getPrice())
                            .status(res.getStatus())
                            .userId(res.getUserId())
                            .giftImg(res.getGiftImg())
                            .sort(res.getSort())
                            .video(res.getVideo())
                            .openTime(res.getOpenTime())
                            .build();
                }).collect(Collectors.toList());
    }

    @Override
    public boolean addOrEdit(AppRoomWishAddOrEditRequest request, Long userId) {
        Gift verify = iGiftService.verify(request.getGiftId());

        Long count = lambdaQuery()
                .eq(RoomWish::getGiftId, request.getGiftId())
                .ne(!request.getId().equals(0L), RoomWish::getId, request.getId())
                .eq(RoomWish::getUserId, userId)
                .count();
        Assert.isTrue(count == 0, "请更换礼物");


        RoomWish one = lambdaQuery()
                .eq(RoomWish::getId, request.getId())
                .one();
        if (CommonUtils.isNull(one)) {
            one = new RoomWish();
        } else {
            one.setNumber(0);
        }
        one.setUserId(userId);
        one.setGiftId(request.getGiftId());
        one.setGiftName(verify.getGiftName());
        one.setPrice(verify.getGiftPrice());
        one.setNumber(request.getNumber());
        one.setCreateTime(new Date());
        one.setStatus(DynamicConstant.CheckStatus.YES);
        one.setGiftImg(verify.getGiftImg());
        one.setSort(request.getSort());
        one.setVideo(verify.getVideo());
        return saveOrUpdate(one);
    }

    @Override
    public boolean open(AppRoomWishCloseRequest request, Long userId) {
        return this.openOrStop(request, userId, DynamicConstant.CheckStatus.YES);
    }

    @Override
    public List<RoomWish> listByUserId(Long userId) {
        return lambdaQuery()
                .eq(RoomWish::getUserId, userId)
                .list();
    }

    @Override
    public boolean stop(AppRoomWishCloseRequest request, Long userId) {
        return this.openOrStop(request, userId, DynamicConstant.CheckStatus.NO);
    }

    @Override
    public AppRoomWishGiveInfoResult giveInfo(AppRoomWishCloseRequest request, Long userId) {
        AppRoomUserSearchRequest request2 = new AppRoomUserSearchRequest();
        request2.setRoomId(request.getRoomId());
        List<AppRoomWishResult> roomWishes = listPage(userId, request2);
        if (roomWishes.isEmpty()) {
            return AppRoomWishGiveInfoResult.builder().build();
        }
        Date openTime = roomWishes.get(0).getOpenTime();

        Set<Long> collect = roomWishes.stream().map(AppRoomWishResult::getGiftId).collect(Collectors.toSet());

        List<RoomGiftRecord> list = iRoomGiftRecordService.lambdaQuery()
                .in(RoomGiftRecord::getGiftId, collect)
                .ge(RoomGiftRecord::getCreateTime, openTime)
                .list();
        if (list.isEmpty()) {
            return AppRoomWishGiveInfoResult.builder().build();
        }
        Set<Long> users = list.stream().map(RoomGiftRecord::getUserId).collect(Collectors.toSet());
        List<RoomGiftRecord> roomGiftRecords = CollectionUtils.emptyList();
        if (list.size() > 2) {
            roomGiftRecords = list.subList(0, 2);
        }else {
            roomGiftRecords = list;
        }
        Set<String> photos = roomGiftRecords.stream().map(RoomGiftRecord::getUserPhoto).collect(Collectors.toSet());
        return AppRoomWishGiveInfoResult.builder()
                .number(users.size())
                .photos(photos)
                .build();
    }

    @Override
    public boolean exchange(AppRoomWishCloseRequest request, Long userId) {
        List<RoomWish> wishList = lambdaQuery().eq(RoomWish::getUserId, userId)
                .eq(RoomWish::getStatus, DynamicConstant.CheckStatus.YES).list();
        Set<Long> giftIds = wishList.stream().map(RoomWish::getGiftId).collect(Collectors.toSet());

        List<Gift> gifts = iGiftService.cutGift(3, giftIds);

        lambdaUpdate().eq(RoomWish::getUserId, userId).remove();

        List<RoomWish> list = CollectionUtils.emptyList();
        for (int i = 0; i < gifts.size(); i++) {
            Gift gift = gifts.get(i);
            RoomWish wish = new RoomWish();
            wish.setGiftId(gift.getId());
            wish.setSort(i + 1);
            wish.setGiftImg(gift.getGiftImg());
            wish.setGiftName(gift.getGiftName());
            wish.setStatus(DynamicConstant.CheckStatus.YES);
            wish.setNumber(10);
            wish.setPrice(gift.getGiftPrice());
            wish.setUserId(userId);
            wish.setVideo(gift.getVideo());
            wish.setOpenTime(new Date());
            list.add(wish);
        }
        return saveBatch(list);
    }

    @Override
    @Async
    public void isRoomWish(Long giftId, Long userId, Long roomId) {
        boolean isRoomWish = lambdaQuery()
                .eq(RoomWish::getGiftId, giftId).eq(RoomWish::getUserId, userId).count() > 0;
        if (isRoomWish) {
            Room verify = iRoomService.verify(roomId);
            AppRoomUserSearchRequest request2 = new AppRoomUserSearchRequest();
            request2.setRoomId(roomId);
            List<AppRoomWishResult> roomWishes = listPage(userId, request2);
            int sum = roomWishes.stream().mapToInt(AppRoomWishResult::getNumber).sum();
            int giveNumber = roomWishes.stream().mapToInt(AppRoomWishResult::getGiveNumber).sum();

            //发送KV消息
            AppRoomWishInfoResult build = AppRoomWishInfoResult.builder()
                    .status(1)
                    .totalNumber(sum)
                    .sendNumber(giveNumber)
                    .wishResults(roomWishes)
                    .build();
            iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_WISH_NUM, JSONObject.toJSONString(build), 0, "", "");


        }
    }

    @Override
    public void delWish(Long id) {
        removeById(id);
    }

    public boolean openOrStop(AppRoomWishCloseRequest request, Long userId, Integer status) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getUserId().equals(userId), "您无权操作");

        lambdaUpdate()
                .eq(RoomWish::getUserId, userId)
                .set(RoomWish::getOpenTime, new Date()).update();

        AppRoomUserSearchRequest request2 = new AppRoomUserSearchRequest();
        request2.setRoomId(verify.getId());
        List<AppRoomWishResult> roomWishes = listPage(userId, request2);
        Assert.notEmpty(roomWishes, "心愿单不能为空");
        Assert.isTrue(roomWishes.size() == 3, "心愿单数量不能小于3");

        int sum = roomWishes.stream().mapToInt(AppRoomWishResult::getNumber).sum();
        int giveNumber = roomWishes.stream().mapToInt(AppRoomWishResult::getGiveNumber).sum();

        AppRoomSetUpdateRequest request1 = new AppRoomSetUpdateRequest();
        request1.setIsWish(status);
        AppRoomSetResult appRoomSetResult = iRoomSetService.updateRoomSet(userId, request1);

        AppRoomWishInfoResult build = AppRoomWishInfoResult.builder()
                .status(appRoomSetResult.getIsWish())
                .totalNumber(sum)
                .sendNumber(giveNumber)
                .wishResults(roomWishes)
                .build();

        iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_WISH_NUM, JSONObject.toJSONString(build), 0, "", "");
        return true;
    }
}
